package com.qire.common.widget.adapter.pager;

import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;

/**
 * 通用简单的基于fragment为子的PagerAdapter，用于TabLayout
 */
public class SimpleFragmentPagerAdapter extends FragmentStatePagerAdapter {

    private static final int BEHAVIOR_SET_USER_VISIBLE_HINT = 0;

    private final FragmentWrapper[] fragmentWrappers;
    private final boolean enableDestroy;

    public SimpleFragmentPagerAdapter(@NonNull FragmentManager fm, FragmentWrapper[] fragmentWrappers) {
        this(fm, fragmentWrappers, true);
    }

    /**
     * 简单的Fragment页面适配器
     * @param fm Fragment管理器
     * @param fragmentWrappers 页面数组
     * @param enableDestroy 控制在页面滑动后，是否销毁回收已滑出页面，true则销毁，false不销毁，默认true
     */
    public SimpleFragmentPagerAdapter(@NonNull FragmentManager fm, FragmentWrapper[] fragmentWrappers, boolean enableDestroy) {
        super(fm, BEHAVIOR_SET_USER_VISIBLE_HINT);
        this.fragmentWrappers = fragmentWrappers;
        this.enableDestroy = enableDestroy;
    }

    @Override
    public int getCount() {
        return fragmentWrappers.length;
    }

    @NonNull
    @Override
    public Fragment getItem(int position) {
        return fragmentWrappers[position].fragment;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return fragmentWrappers[position].title;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        if(enableDestroy) {
            super.destroyItem(container, position, object);
        }
    }

    /**
     * Fragment包装器,绑定一个fragment的title
     */
    public static class FragmentWrapper {
        public final String title;
        public final Fragment fragment;
        public FragmentWrapper(String title, Fragment fragment) {
            this.title = title;
            this.fragment = fragment;
        }
    }
}